<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <title>单例模式-惰性单例</title>
</head>

<body>
    <h2>惰性单例</h2>
    <h2>只在需要的时候加载</h2>
    <button id="loginBtn">登录</button>

    <script type="text/javascript">

        var createAlertLayout = (function () {
            var div
            return function(){
                if(!div){
                    div = document.createElement('div')
                    div.innerHTML = '我是一个弹窗'
                    div.style.display = 'none'
                    document.body.appendChild(div)
                }
                return div
            }
        })()
        document.querySelector('#loginBtn').addEventListener('click', function () {
            var alertLayout = createAlertLayout()
            alertLayout.style.display = alertLayout.style.display ==='block'?'none':'block'
        }, false)

    </script>

</body>

</html>